#pragma once

#include <string>
#include <vector>
#include <chrono>  // For timestamp
#include <iomanip> // for put_time
#include <sstream> // for ostringstream

#include "ShoppingCart.h"      // 需要 CartItem
#include "User.h"

class UserController;

enum class OrderStatus
{
    UNPAID,              // 未支付
    PAID,                // 已支付
    CANCELLED,           // 已取消
    FAILED_STOCK_FREEZE, // 库存冻结失败
    PAYMENT_FAILED       // 支付失败
};

// 将订单状态转换为字符串以便显示
inline std::string orderStatusToString(OrderStatus status)
{
    switch (status)
    {
    case OrderStatus::UNPAID:
        return "未支付";
    case OrderStatus::PAID:
        return "已支付";
    case OrderStatus::CANCELLED:
        return "已取消";
    case OrderStatus::FAILED_STOCK_FREEZE:
        return "库存冻结失败";
    case OrderStatus::PAYMENT_FAILED:
        return "支付失败";
    default:
        return "未知状态";
    }
}

class Order
{
public:
    struct OrderItem
    {
        std::string productId;
        std::string productName;
        int quantity;
        double unitPrice; // 成交单价
        int sellerId;
    };

private:
    std::string orderId;
    int customerId;
    std::vector<OrderItem> items;
    double totalAmount;
    OrderStatus status;
    std::chrono::system_clock::time_point orderTime;

    std::string generateOrderId(); // 辅助函数生成唯一订单ID

public:
    // 构造函数：从购物车创建订单，并尝试冻结库存
    Order(int custId, const ShoppingCart &cart, ProductController &productCtrl);
    Order(const json &j_order);

    json toJson() const;
    // Getters
    const std::string &getOrderId() const;
    int getCustomerId() const;
    const std::vector<OrderItem> &getItems() const;
    double getTotalAmount() const;
    OrderStatus getStatus() const;
    std::string getOrderTimeString() const;

    void setStatus(OrderStatus newStatus);

    // 支付处理
    bool processPayment(User &customer, UserController &userCtrl, ProductController &productCtrl);
    // 取消订单 (通常意味着解冻库存)
    void cancelOrder(ProductController &productCtrl);
};
